﻿/*****  Action when document ready  *****/
$(document).ready(function () {
    // register qla custom class
    registerStyleClass();
    autoValidDate();
    autoTrimInput();
    autoCloseDateWarn();
    removeEmptyRowDataGrid();
    preventSubmitWhenWarn();
    preventContextMenuCommandLink();

  
    // Purpose: set auto height for filter items of combobox (fix issue 4594)
    setAutoHeightForComboBoxFilters();

    // setup for stack menu
    qla_setupForStackMenu();
    initInputMethod();
    loadMenu();
});

/***** private function *****/

function initInputMethod() {
    Mudim.BeforeInit = function () {
        Mudim.showPanel = false;
        var method = $.cookie('qla_im');
        method = method == null ? 0 : method;

        if (method == 0) {
            disableVietnamese();
        }
        else {
            enableVietnamese();
        }
    };
    Mudim.AfterInit = function () {
        Mudim.showPanel = false;
        var method = $.cookie('qla_im');
        method = method == null ? 0 : method;
        if (method == 0) {
            disableVietnamese();
        }
        else {
            enableVietnamese();
        }
    };
    Mudim.Init();
}

function preventContextMenuCommandLink() {
    $(document).on('contextmenu', '.ui-commandlink', function (e) {
        e.preventDefault();
        return false;
    });
}



function loadMenu() {
    var breadcrumb = '';
    var path = window.location.pathname;
    var selector = '.ui-menuitem a[href="' + path + '"]';
    var jq = $('[id$=panelMenu]');
    var menuitemLinks = jq.find('.ui-menuitem-link:not(.ui-state-disabled)');
    var headers = jq.children('.ui-panelmenu-panel:not(.ui-state-disabled)');

    // bind sự kiện click cho các menu item
    var mlinks = jq.find('[href*=THIDUA]');
    mlinks.one('click', function (e) {
        var cvalue = $(this).attr('id');
        $.cookie('qla_menu', cvalue,
        {
            path: '/'
        });
    });
    // tự động collapse tất cả menu lại
    $.each(headers, function () {
        var c = $(this).children('h3');
        if ($(this).children('div').is(':visible')) {
            c.click();
        }
        c.removeClass('ui-state-hover');
        c.addClass('ui-state-default');
    });

    // tìm menu đang được chọn để expand
    var link;
    var menu;

    if (menuitemLinks.is(selector)) {
        // nếu url trang hiện tại có trong menu
        link = $(selector);

        // nếu url trang hiện tại có nhiều hơn 1 trong menu thì lấy từ cookie
        if (link.length != 1) {
            var id = $.cookie('qla_menu');
            link = $('#' + id);
        }
    }
    else {
        var folders = path.split('/');
        folders.shift();
        var ref_folder = document.referrer.replace(window.location.protocol + '//' + window.location.host + '/THIDUA', 'THIDUA').split('/');
        // trong trường hợp có referer thì lấy từ cookie
        if (document.referrer != '' && document.referrer.indexOf(document.location.host) !== -1/*&& $.inArray(ref_folder[ref_folder.length - 2], folders) !=  - 1*/) {
            var lid = $.cookie('qla_menu');
            link = $('[id$="' + lid + '"]');
        }
        else {
            folders.pop();
            var folderpath = folders.join('/');
            link = jq.find('.ui-menuitem a[href*="' + folderpath + '"]');
            if (link.length > 1) {
                link = $(link[0]);
            }
            if (link.length == 0) {
                var lid = $.cookie('qla_menu');
                //                link = $('#' + lid);
                link = $('[id$="' + lid + '"]');
            }
        }
    }
    if (link.length == 1) {
        link.addClass('ui-state-active');
        link.prepend('<span class="ui-icon ui-icon-check"/>');
        menu = link.parent();

        while (!menu.is('.ui-panelmenu-content')) {
            var text = link.find('.ui-menuitem-text').text();
            var href = link.attr('href');
            var breaditem = createBreadItem(text, href);
            breadcrumb = breaditem + breadcrumb;
            link = getParentMenuLink(menu);
            menu = getParentMenu(menu);
            if (!menu.children('.ui-menu-list, ui-menuitem').is(':visible')) {
                link.click();
            }
        }
        var header = menu.parent();
        var headerlink = header.children('h3');
        if (!menu.children('div').is(':visible')) {
            headerlink.click();
        }
        var headertext = headerlink.find('a').text();
        var headerhref = headerlink.find('a').attr('href');
        var headerbreaditem = createBreadItem(headertext, headerhref);
        breadcrumb = headerbreaditem + breadcrumb;
    }

    $('.ui-breadcrumb>ul').append(breadcrumb);
    window.setTimeout(function () {
        $('[id$=panelMenu]').parent().scrollTo($('.ui-menuitem-link.ui-state-active'), 1111);
    },
555);

}

function preventSubmitWhenWarn() {
    if (typeof widget_bodyForm_jsmessage === "undefined") {
        PrimeFaces.cw('Growl', 'widget_bodyForm_jsmessage',
        {
            id: 'bodyForm:jsmessage', sticky: false, life: 7777, escape: true, msgs: []
        });
    }
    var p = jQuery.extend(true,
    {
},
    PrimeFaces);
PrimeFaces.ab = function (cfg, ext) {
    if (cfg.source === 'bodyForm:btnSave' || cfg.source === 'bodyForm:btnSearch') {
        setTimeout(function () {
            if (widget_bodyForm_jsmessage.getJQ().html() === '') {
                p.ab(cfg, ext);
            }
            else {
                return false;
            }
        },
555);
    }
    else {
        p.ab(cfg, ext);
    }

}

var x = jQuery.extend(true,
    {
},
    widget_bodyForm_jsmessage);
widget_bodyForm_jsmessage.show = function (msg) {
    qla_delaysubmit();
    x.show(msg);
};

}

function registerStyleClass() {

    // qla-money
    $(document).on('keyup', '.qla-money', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;
        if (code != 9) {
            $(this).parseNumber({
                format: "#,###", locale: "vn"
            });
            $(this).formatNumber({
                format: "#,###", locale: "vn"
            });
        }
    });

    $('.qla-money').trigger('keyup');
    

    // qla-capitalize
    $(document).on("keyup", '.qla-capitalize', function () {
        var txt = $(this).val().toLowerCase();
        $(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
            return $1.toUpperCase();
        }));
    });

    // qla-upper
    $(document).on("keyup", '.qla-upper', function () {
        var txt = $(this).val().toUpperCase();
        $(this).val(txt);
    });

    // qla-lower
    $(document).on("keyup", '.qla-lower', function () {
        var txt = $(this).val().toLowerCase();
        $(this).val(txt);
    });

    // qla-no-enter
    $(document).on("keypress", '.qla-no-enter, .hasDatepicker', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;
        if (code == 13) {
            e.preventDefault();
            return false;

        }
    });

    // qla-number-only
    $(document).on("keyup", '.qla-number-only', function () {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
    });
    $(document).on("keydown", '.qla-number-only', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;

        if (code == 46 || code == 8 || code == 9 || code == 27 || code == 13 ||
        // Allow: Ctrl+A
(code == 65 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
(code >= 35 && code <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (e.shiftKey || (code < 48 || code > 57) && (code < 96 || code > 105)) {
                return false;
            }
        }
    });

    // qla-float-only
    $(document).on("keyup", '.qla-float-only', function () {
        $(this).val($(this).val().replace(/[^0-9]+\.[0-9]/g, ''));
    });
    $(document).on("keydown", '.qla-float-only', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;

        if (code == 46 || code == 8 || code == 9 || code == 27 || code == 13 || code == 190 || code == 110 ||
        // Allow: Ctrl+A
(code == 65 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
(code >= 35 && code <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (e.shiftKey || (code < 48 || code > 57) && (code < 96 || code > 105)) {
                return false;
            }
        }
    });

    // qla-tree-table
    $(document).on("dblclick", '.qla-tree-table', function () {
        detailDialog.show();
    });

    // qla-no-space
    $(document).on("keyup", '.qla-no-space', function () {
        $(this).val($(this).val().replace(/ /g, ''));
    });
    $(document).on("keydown", '.qla-no-space', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;
        if (code == 32)
            return false;
    });
    


    // qla-select-last
    //    $(document).on("load", '.qla-select-last', function (e) {
    //        var eid = $(this).attr('id').split(':')[1];
    //        $('[id*=' + eid + ']:last').prop('checked', true);
    //        $('[for*=' + eid + ']:last').click();
    //    });
    $('.qla-select-last').each(function (e) {
        var eid = $(this).attr('id').split(':')[1];
        $('[id*=' + eid + ']:last').prop('checked', true);
        $('[for*=' + eid + ']:last').click();
    });

    // qla-select-first
    //    $(document).on("load", '.qla-select-first', function (e) {
    //        var eid = $(this).attr('id').split(':')[1];
    //        $('[id*=' + eid + ']:first').prop('checked', true);
    //        $('[for*=' + eid + ']:first').click();
    //    });
    $('.qla-select-first').each(function (e) {
        var eid = $(this).attr('id').split(':')[1];
        $('[id*=' + eid + ']:first').prop('checked', true);
        $('[for*=' + eid + ']:first').click();
    });
}

function autoTrimInput() {
    $(document).on("blur", 'input[type="text"]:not(.ui-autocomplete-input)', function () {
        var val = $(this).val().trim();
        $(this).val(val);
    });
    $(document).on("keypress", 'input[type="text"]:not(.qla-no-enter, .hasDatepicker)', function (e) {
        var code;
        if (!e)
            var e = window.event;
        if (e.keyCode)
            code = e.keyCode;
        else if (e.which)
            code = e.which;
        if (code == 13) {
            var val = $(this).val().trim();
            $(this).val(val);
            return true;
        }
    });
}

function autoValidDate() {
    $(document).on('focusin', '.hasDatepicker', function () {
        $(this).mask('99/99/9999');
    });

    //$( ".hasDatepicker" ).datepicker( "option", "beforeShowDay", $.datepicker.noWeekends);
    $(document).on("blur", '.hasDatepicker', function (e) {
        var val = $(this).val();
        if (val != '' && val != '__/__/____' && val != 'dd/MM/yyyy') {
            try {
                var date = $.datepicker.parseDate('dd/mm/yy', val);
                closeMessage();
                return true;
            }
            catch (e) {
                $(this).val('');
                showMessage('warn', 'Sai định dạng ngày tháng hoặc ngày tháng không hợp lệ.');
                $(this).focus();
                //qla_delaysubmit();
            }
        }
        else {
            closeMessage();
            return true;
        }
    });
}

// auto close date warning when submit
function autoCloseDateWarn() {
    $(document).on("click", ':submit', function () {
        closeMessage();
    });
}

// public function
function qla_focus(elementID) {
    var element;
    if (elementID != '') {
        element = $($.find(':input[id*=' + elementID + ']:first'));
        var val = element.val();
        element.val('');
        element.focus();
        element.val(val);
    }
}

function showMessage(type, message) {
    $(function () {
        PrimeFaces.cw('Growl', 'widget_bodyForm_jsmessage',
        {
            id: 'bodyForm:jsmessage', sticky: false, life: 3333, escape: true, msgs: [{ summary: message, detail: "", severity: 'warn'}]
        });
    });
}

function closeMessage() {
    $('div[id*=jsmessage]').html('');
}

function addState(element, type) {
    var state = 'ui-state-' + type;
    $(element).addClass(state);
    var labelfor = $(element).attr('id').split(':')[1];
    $('label[for*=' + labelfor + ']').addClass(state);
}

function removeState(element, type) {
    var state = 'ui-state-' + type;
    $(element).removeClass(state);
    var labelfor = $(element).attr('id').split(':')[1];
    $('label[for*=' + labelfor + ']').removeClass(state);
}

function qla_ajaxdate(eid) {
    var element;
    var val;
    if (eid != '') {
        element = element = $('span[id$=' + eid + ']>input');
        val = element.val();
        if (val == '' || val == 'dd/MM/yyyy' || val == '__/__/____')
            return false;
        try {
            var date = $.datepicker.parseDate('dd/mm/yy', val);
            return true;
        }
        catch (e) {
            return false;
        }
    }
}

function removeEmptyRowDataGrid() {
    $('.ui-datagrid-row:not(:has(>td>div))').hide();
    $('.ui-datagrid-row hr:last').hide();
}

function qla_ajaxrequire(eid) {
    var element;
    var val;
    if (eid != '') {
        element = element = $('input[id*=' + eid + ']');
        val = element.val();
        if (val == '')
            return false;
        else
            return true;
    }
}

function selectLaw(lawcode_clientid, lawcode) {
    try {
        if (window.opener.document.getElementById(lawcode_clientid) != null)
            window.opener.document.getElementById(lawcode_clientid).value = lawcode;
        window.opener.document.getElementById("bodyForm:btnSearch").click();
        //window.opener.location.reload(true);
        //window.opener.$("#bodyForm").submit();
        //self.close();
    }
    catch (e) {
        alert(e);
    }
    return false;
}

function qla_delaysubmit() {
    var ele = $('[id*=btnSave], [id*=btnSearch]');
    ele.attr('disabled', true);
    setTimeout(function () {
        ele.attr('disabled', false);
    },
333);
}

function setAutoHeightForComboBoxFilters() {
    $(document).on('keyup', '.ui-selectonemenu-filter', function () {
        $('.ui-selectonemenu-items-wrapper').each(function () {
            var height = $(this).css('height');
            if (height == '0px') {
                $(this).css('height', 'auto');
            }
        })
    });
}

function getParentMenu(menu) {
    var parentmenu = menu.parent().parent();
    return parentmenu;
}

function getParentMenuLink(menu) {
    var link = getParentMenu(menu).children('.ui-menuitem-link');
    return link;
}

function createBreadItem(text, href) {
    var ref = href;
    if (typeof ref == 'undefined') {
        ref = "#";
    }
    var html = '';
    html += '<li class="ui-breadcrumb-chevron ui-icon ui-icon-triangle-1-e"><\/li>';
    html += '<li role="menuitem">';
    html += '<a href="' + ref + '" class="ui-menuitem-link ui-corner-all">';
    html += '<span class="ui-menuitem-text">' + text + '</span>';
    html += '<\/a><\/li>';
    return html;
}

function qla_tickmenu(href) {
    var val = $('a[href="' + href + '"]:first').attr('id');
    $.cookie('qla_menu', val,
    {
        path: '/'
    });
}

function qla_setupForStackMenu() {
    var timer = null;
    $('.ui-stack').hover(function () {
        clearTimeout(timer);
        $(this).stop();
        $(this).animate({
            "opacity": 1
        },
200);
        //$(this).css('cssText', 'bottom: -5px !important');
        if (!$('.ui-stack ul').hasClass('openStack')) {
            $('.ui-stack>img').click();
        };
    },
    function () {
        var stack = $(this);
        stack.stop();
        stack.animate({
            "opacity": 0.25
        },
1000);
        timer = setTimeout(function () {
            if ($('.ui-stack ul').hasClass('openStack')) {
                $('.ui-stack>img').click();
            };
            //stack.css('cssText', 'bottom: -30px !important');
        },
1000);
    });
}

function enableVietnamese() {
    $('[id$=input-method-off]').hide();
    $('[id$=input-method-on]').show();
    Mudim.SetMethod(4);
    $.cookie('qla_im', Mudim.method,
    {
        path: '/'
    });
}

function disableVietnamese() {
    $('[id$=input-method-off]').show();
    $('[id$=input-method-on]').hide();
    Mudim.SetMethod(0);
    $.cookie('qla_im', Mudim.method,
    {
        path: '/'
    });
}
function fixPFDialogToggleMaximize(dlg) {
    if (undefined == dlg.doToggleMaximize) {
        dlg.doToggleMaximize = dlg.toggleMaximize;
        dlg.toggleMaximize = function () {
            this.doToggleMaximize();

            var marginsDiff = this.content.outerHeight() - this.content.height();
            var newHeight = this.jq.innerHeight() - this.titlebar.outerHeight() - marginsDiff;
            this.content.height(newHeight);
        };
    }
}